package com.cskaoyan.duolai.clean.user.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.cskaoyan.duolai.clean.dto.BooleanResDTO;
import com.cskaoyan.duolai.clean.dto.OpenIdResDTO;
import com.cskaoyan.duolai.clean.user.client.SmsCodeApi;
import com.cskaoyan.duolai.clean.user.client.WechatApi;
import com.cskaoyan.duolai.clean.user.converter.CommonUserConverter;
import com.cskaoyan.duolai.clean.user.dao.entity.CommonUserDO;
import com.cskaoyan.duolai.clean.user.request.LoginForCustomerCommand;
import com.cskaoyan.duolai.clean.user.request.LoginForWorkCommand;
import com.cskaoyan.duolai.clean.user.dto.LoginDTO;
import com.cskaoyan.duolai.clean.user.dto.ServeProviderDTO;
import com.cskaoyan.duolai.clean.user.service.ICommonUserService;
import com.cskaoyan.duolai.clean.user.service.ILoginService;
import com.cskaoyan.duolai.clean.user.service.IServeProviderService;
import com.cskaoyan.duolai.clean.common.constants.CommonStatusConstants;
import com.cskaoyan.duolai.clean.common.constants.ErrorInfo;
import com.cskaoyan.duolai.clean.common.constants.UserType;
import com.cskaoyan.duolai.clean.common.enums.SmsBussinessTypeEnum;
import com.cskaoyan.duolai.clean.common.expcetions.BadRequestException;
import com.cskaoyan.duolai.clean.common.expcetions.CommonException;
import com.cskaoyan.duolai.clean.common.utils.JwtTool;
import com.cskaoyan.duolai.clean.common.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ILoginServiceImpl implements ILoginService {

    @Resource
    private ICommonUserService commonUserService;

    @Resource
    private JwtTool jwtTool;

    @Resource
    private IServeProviderService serveProviderService;
    @Resource
    private WechatApi wechatApi;
    @Resource
    private SmsCodeApi smsCodeApi;

    @Resource
    CommonUserConverter commonUserConverter;

    @Override
    public LoginDTO loginForWorker(LoginForWorkCommand loginForWorkCommand) {

        // 1. 数据校验，验证码为空，则抛出异常
        if (StringUtils.isEmpty(loginForWorkCommand.getVeriryCode())) {
            throw new BadRequestException("验证码错误，请重新获取");
        }

        // 2. 服务调用foundation服务校验验证码是否正确，如果校验不成功则抛出异常
        BooleanResDTO verifyResult = smsCodeApi.verify(
                loginForWorkCommand.getPhone(),
                SmsBussinessTypeEnum.SERVE_STAFF_LOGIN,
                loginForWorkCommand.getVeriryCode());

        if (verifyResult == null || !verifyResult.getIsSuccess()) {
            throw new BadRequestException("验证码错误，请重新获取");
        }

        // 3. 登录校验，根据手机号获取服务人员信息
        ServeProviderDTO serveProviderDTO = serveProviderService.findByPhone(loginForWorkCommand.getPhone());

        // 4. 如果根据手机号未查询出信息，说明是首次登录，需要保存其信息
        if (serveProviderDTO == null) {
            serveProviderDTO = serveProviderService.addServeProvider(loginForWorkCommand.getPhone());
        }

        // 5. 生成登录token，用户类型为UserType.WORKER
        String token = jwtTool.createToken(
                serveProviderDTO.getId(),
                serveProviderDTO.getName(),
                serveProviderDTO.getAvatar(),
                UserType.WORKER);

        return new LoginDTO(token);
    }
    
    @Override
    public LoginDTO loginForCommonUser(LoginForCustomerCommand loginForCustomerCommand) {

        // 1. 调用foundation服务wechatApi.getOpenId, code换openId
        OpenIdResDTO openIdResDTO = wechatApi.getOpenId(loginForCustomerCommand.getCode());
        if (openIdResDTO == null || StringUtils.isEmpty(openIdResDTO.getOpenId())) {
            throw new CommonException(ErrorInfo.Code.LOGIN_TIMEOUT, ErrorInfo.Msg.REQUEST_FAILD);
        }

        // 2. 根据openId查询用户信息
        CommonUserDO commonUserDO = commonUserService.findByOpenId(openIdResDTO.getOpenId());

        // 3. 如果未从数据库查到，需要新增数据
        if (commonUserDO == null) {

            // 转换请求对象为DO
            commonUserDO = commonUserConverter.loginForCustomerCommandToCommonUserDO(loginForCustomerCommand);

            // 设置openId
            commonUserDO.setOpenId(openIdResDTO.getOpenId());

            // 设置nickName: "普通用户"+ RandomUtil.randomInt(10000,99999)
            commonUserDO.setNickname("普通用户" + RandomUtil.randomInt(10000, 99999));

            // 设置状态为正常
            commonUserDO.setStatus(CommonStatusConstants.USER_STATUS_NORMAL);

            // 保存用户信息
            commonUserService.save(commonUserDO);
        }

        // 4. 根据用户信息构建token，userType为UserType.C_USER
        String token = jwtTool.createToken(
                commonUserDO.getId(),
                commonUserDO.getNickname(),
                commonUserDO.getAvatar(),
                UserType.C_USER);

        return new LoginDTO(token);
    }
}
